package com.baosight.risk.web.shiro;

import com.baosight.risk.api.xtzy.IXtsqMenuAuthoService;
import com.baosight.risk.api.xtzy.IXtzyUserService;
import com.baosight.risk.common.utils.ShiroUtils;
import com.baosight.risk.service.system.entity.SysMenu;
import com.baosight.risk.service.xtzy.entity.XtzyUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
public class ShiroDbRealm extends AuthorizingRealm {
    @Autowired
    private IXtsqMenuAuthoService menuAuthoService;

    @Autowired
    private IXtzyUserService userService;


    @Override
    public void setName(String name) {
        super.setName("shiroDbRealm");
    }

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        XtzyUser sysUser = ShiroUtils.getUser();
        // 功能列表
        Set<String> menus;
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 管理员拥有所有权限
        if (sysUser.isAdmin()) {
            info.addRole("admin");
            info.addStringPermission("*:*:*");
        } else {
            List<SysMenu> menuList = menuAuthoService.getMenuByCompAndUser(sysUser.getExt1(), sysUser);
            List<String> keyList = menuList.stream().map(SysMenu::getMenuKey).collect(Collectors.toList());
            menus = new HashSet(keyList);
            if (CollectionUtils.isNotEmpty(menus)) {
                menus.remove("");
            }
            // 角色加入AuthorizationInfo认证对象
            info.setRoles(menus);
            // 权限加入AuthorizationInfo认证对象
            info.setStringPermissions(menus);
        }
        return info;
    }

    /**
     * 登录认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        log.info(upToken.toString());
        String username = upToken.getUsername();
        XtzyUser sysUser = userService.selectByName(username);
        log.info("登陆认证：" + sysUser.toString());
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(sysUser, upToken.getPassword(), getName());
        return info;
    }

    /**
     * 清理缓存权限
     */
    public void clearCachedAuthorizationInfo() {
        this.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }

}
